import React, {Component} from "react";
import {ListView, Toast} from "antd-mobile";
import {restApiRequest} from "../Public/Api/Public";
import LoopViewPager from "./LoopViewPage";
import LazyLoad from "react-lazyload";
import TabBar from '../Public/Components/TabBar'

//每页显示数据的条数
// const pageSize = 999;
//每页显示数据的条数
const pageSize = 5;
let pageNum = 1;
let ProductInfoList = [];
export default class HomePage extends Component {

    constructor(props, context) {
        super(props, context);
        this.state = {
            dataSource: new ListView.DataSource({
                rowHasChanged: (row1, row2) => row1 !== row2,
            }),
            projectdataSource: new ListView.DataSource({
                rowHasChanged: (row1, row2) => row1 !== row2,
            }),
            foot: 0,
            isRefreshing: false,
        };
    }

    componentWillMount() {
        ProductInfoList = [];
        pageNum = 1;
        let param = {page_size: pageSize, page_num: pageNum};
        let jsonData = restApiRequest.getSign(param);
        let url_topic = '/shop/api/homeProductTopicList';
        let url_home_topic = '/shop/api/homeTopicList';
        this.fetchData(url_topic, jsonData);
        this.homeTopicList(url_home_topic, jsonData);
    }

    //获取商品列表
    fetchData(url, jsonData) {
        restApiRequest.fetchp(url, jsonData).then((response) => {
            if (!response.ok) {
                var error = new Error(response.statusText);
                error.response = response;
                throw error;
            } else {
                return response.json();
            }
        }).then((response_json) => {
            console.log(response_json);
            if (response_json.code === '0000') {
                let responseData = response_json.data;
                //请求结果有数据
                if (responseData.major_product_list.length > 0) {
                    //请求数据小于5数据加载完
                    if (responseData.major_product_list.length < pageSize) {
                        //加载完毕
                        this.setState({foot: 1});
                    } else {
                        //隐藏
                        this.setState({foot: 0});
                    }
                    if (responseData.major_product_list != null) {
                        //每次请求结果push到商品列表数组进行渲染
                        for (var i = 0; i < responseData.major_product_list.length; i++) {
                            ProductInfoList.push(responseData.major_product_list[i]);
                        }
                        this.setState({
                            dataSource: this.state.dataSource.cloneWithRows(ProductInfoList),
                        });
                    }
                } else {
                    this.setState({foot: 1});
                }
                this.setState({isRefreshing: false})
                // this.setState({
                //   dataSource: this.state.dataSource.cloneWithRows(responseData.major_product_list),
                // });
            } else {
                return Toast.offline(response_json.msg, 2)
            }
        }).catch((ex) => {
            console.log(ex);
        });
    }

    //专题列表
    homeTopicList(url, jsonData) {
        this.setState({foot: 2});
        restApiRequest.fetchp(url, jsonData).then((response) => {
            if (!response.ok) {
                var error = new Error(response.statusText);
                error.response = response;
                throw error;
            } else {
                return response.json();
            }
        }).then((response_json) => {
            console.log(response_json);
            this.setState({
                projectdataSource: this.state.projectdataSource.cloneWithRows(response_json.data),

            });

        }).catch((ex) => {
            console.log(ex);
        });
    }

    //点击跳转详情
    jumpRow(rowData) {
        this.props.history.push({
            pathname: '/ProductDetail',
        })
        localStorage.setItem('ProductDetail', JSON.stringify(rowData))
    }

    jumpTopRow(rowData) {
        // this.context.router.push({
        //   pathname: '/TopicList',
        // })
        window.location.href = "https://api.hidizhu.com/api/WebView/topic?is_wx=1&topic_id=" + rowData.id;
    }

    //加载更多
    onEndReached() {
        if (this.state.foot != 0) {
            return;
        }
        this.setState({
            foot: 2,
        });
        pageNum++;
        console.log('当前页数:' + pageNum);
        let param = {page_num: pageNum, page_size: pageSize};
        let jsonData = restApiRequest.getSign(param);
        let product_url = '/shop/api/majorlist';
        this.fetchData(product_url, jsonData);
    }

    render() {

        const renderList = (rowData, sectionID, rowID) => {

            let big = '0';
            let small = '0';
            if (rowData.price != undefined) {
                let price_array = rowData.price.split('.');
                big = price_array[0];
                small = price_array[1].substr(0, 1);
            } else {
            }

            if (rowData.is_topic === 1) {
                return (
                    <div
                        key={rowID}
                        onClick={() => this.jumpRow(rowData)}
                        className="home-list"
                    >
                        <section className="home-list-imgbox">
                            <LazyLoad
                                offset={100}
                                debounce={500}
                                placeholder={
                                    <section className="home-list-lazyload">
                                        <svg className="home-list-placeholder">
                                            <use xlinkHref={'#icon-ico_page_bottom_dog'}></use>
                                        </svg>
                                    </section>
                                }
                            >
                                <img className="home-list-img" src={rowData.topic_cover_pic_url}/>
                            </LazyLoad>
                        </section>
                    </div>
                )
            } else {
                return (
                    <div
                        key={rowID}
                        onClick={() => this.jumpRow(rowData)}
                        className="home-list"
                    >
                        <section className="home-list-imgbox">

                            <LazyLoad
                                offset={100}
                                debounce={500}
                                placeholder={
                                    <section className="home-list-lazyload">
                                        <svg className="home-list-placeholder">
                                            <use xlinkHref={'#icon-ico_page_bottom_dog'}></use>
                                        </svg>
                                    </section>
                                }
                            >
                                <img className="home-list-img" src={rowData.top_image_url}/>
                            </LazyLoad>

                            <section className="home-list-imgtips">
                                <svg>
                                    <use xlinkHref='#icon-ico_corner_tag'></use>
                                </svg>
                                <section className="home-list-tips">
                                    <p className="home-list-tipstext">{rowData.use_scope}</p>
                                    <section className="home-list-price">
                                        <span>￥</span>
                                        <span>{big}</span>
                                        <span>.{small}</span>
                                    </section>
                                </section>
                            </section>

                            <section className="home-arrows-box">
                                <div className="home-arrows-left"/>
                                <div className="home-arrows-right"/>
                            </section>
                        </section>

                        <section className="home-text-box">
                            <p>{rowData.major_product_shortname}</p>
                            <p>{rowData.major_product_name}</p>
                        </section>

                    </div>
                )
            }
        };

        const renderFooter = () => {
            if (this.state.foot === 0) {            //上滑加载更多
                return (
                    <div className="hom-list-footer">
                        <svg className="hom-list-footer-icon">
                            <use xlinkHref='#icon-ico_page_bottom_dog'></use>
                        </svg>
                        <p
                            className="hom-list-footer-text">往上滑加载更多...</p>
                    </div>);
            } else if (this.state.foot === 1) {    //加载完毕
                return (
                    <section className="hom-list-footer">
                        <svg className="hom-list-footer-icon">
                            <use xlinkHref={'#icon-ico_page_bottom_dog'}></use>
                        </svg>
                        <p className="hom-list-footer-text">我是有底线的</p>
                    </section>);
            } else if (this.state.foot === 2) {     //加载中
                return (
                    <div className="hom-list-footer">
                        <svg className="hom-list-footer-icon">
                            <use xlinkHref='#icon-ico_page_bottom_dog'></use>
                        </svg>
                        <p className="hom-list-footer-text">拼命加载中...</p>
                    </div>);
            }
        };

        const projectrenderList = (rowData, sectionID, rowID) => {
            return (
                <div className="home-TopicList-list"
                     key={rowID}
                     onClick={() => this.jumpTopRow(rowData)}>
                    <img src={rowData.topic_cover_pic_url} className="home-TopicList-img"/>
                </div>

            )

        };

        return (
            <div>
                <TabBar
                    HomeActive={true}
                />
                <LoopViewPager/>
                <div className="home-classify-wrap">
                    <Classify
                        title={'门票'}
                        icon={'#icon-ico_ticket'}
                        onPress={() => this.props.history.push({
                            pathname: '/ProductList',
                            search: '2',
                        })}
                    />
                    <Classify
                        title={'一日游'}
                        icon={'#icon-ico_shoe'}
                        onPress={() => this.props.history.push({
                            pathname: '/ProductList',
                            search: '3',
                        })}
                    />
                    <Classify
                        title={'文化演出'}
                        icon={'#icon-ico_camera'}
                        onPress={() => this.props.history.push({
                            pathname: '/ProductList',
                            search: '4',
                        })}
                    />
                    <Classify
                        title={'生活休闲'}
                        icon={'#icon-ico_fishing'}
                        onPress={() => this.props.history.push({
                            pathname: '/ProductList',
                            search: '5',
                        })}
                    />
                </div>
                <Title text={'地主专题'} onPress={() => this.props.history.push({
                    pathname: '/TopicList',

                })}/>
                <ListView
                    dataSource={this.state.projectdataSource}
                    useBodyScroll
                    renderRow={projectrenderList}
                    stickyHeader
                />
                <Title text={'地主推荐'} onPress={() => this.props.history.push({
                    pathname: '/MajorList',
                })}/>
                <ListView
                    dataSource={this.state.dataSource}
                    useBodyScroll
                    renderRow={renderList}
                    renderFooter={renderFooter}
                    onEndReached={this.onEndReached.bind(this)}
                    onEndReachedThreshold={10}
                    stickyHeader
                />
            </div>
        )
    }

}


class Title extends Component {

    render() {

        return (
            <section className="home-title-wrap" onClick={this.props.onPress}>
                <div className="home-title-line"/>
                <div className="home-title-box">
                    <span>{this.props.text}</span>
                    <svg>
                        <use xlinkHref='#icon-ico_more_arrow1'></use>
                    </svg>
                </div>
            </section>
        )
    }

}

class Classify extends Component {

    render() {
        return (
            <section className="home-classify-box" onClick={this.props.onPress}>
                <svg>
                    <use xlinkHref={this.props.icon}></use>
                </svg>
                <span>{this.props.title}</span>
            </section>
        )
    }
}